<template>
  <div class="app-container">
    <div>
      <el-button type="primary" plain @click="showneibufawenDialog">内部发文</el-button>
    </div>
    <!-- {{list}} -->
    <div style="padding: 10px" />
    <el-table
      v-loading="listLoading"
      :data="list"
      style="width: 100%"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column label="状态" align="center" width="100px">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.sta==0" type="warning">审核</el-tag>
          <el-tag v-if="scope.row.sta==1" type="success">通过</el-tag>
          <el-tag v-if="scope.row.sta==3" type="danger">拒绝</el-tag>
          <el-tag v-if="scope.row.sta==4" type="info">撤销</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="申请时间" align="center" width="110px">
        <template slot-scope="scope">
          {{ getFormatedTimeStr(scope.row.createTime) }}
        </template>
      </el-table-column>

      <el-table-column label="标题" align="center">
        <template slot-scope="scope">
          {{ scope.row.biaoti }}
        </template>
      </el-table-column>

      <el-table-column label="内容摘要" align="center">
        <template slot-scope="scope">
          {{ scope.row.neirong }}
        </template>
      </el-table-column>

      <el-table-column label="分发范围" align="center">
        <template slot-scope="scope">
          <span v-for="(item,index) in scope.row.readers" :key="index">
            {{ item.name }}、
          </span>
        </template>
      </el-table-column>

      <el-table-column label="相关附件" align="center">
        <template slot-scope="scope">
          <p v-for="(item,index) in scope.row.attaches " :key="index" style="">
            <el-link :href="item.path" type="primary" target="_blank">{{ item.name }}</el-link>
          </p>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" plain @click="seeDetail(scope.row.id)">详情 </el-button>
          <el-button v-if="(scope.row.sta !== 4)" size="mini" type="primary" plain @click="revertApply(scope.$index)">撤回</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="padding: 10px" />
    <el-pagination
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageCount"
      layout="total, sizes, prev, pager, next, jumper"
      :total="dataTotal"
      @size-change="onPageSizeChange"
      @current-change="onCurrentPageChange"
    />

    <el-dialog title="内部发文" :visible.sync="neibufawenDialog.visible" width="40%" :close-on-click-modal="false" top="5vh">
      <div>
        <el-form ref="form" label-width="120px">
          <el-form-item label="文件类型">
            <el-select v-model="neibufawenDialog.fileTag" placeholder="请选择" style="width: 100%;">
              <el-option v-for="item in rangeArr" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="标题">
            <el-input v-model="neibufawenDialog.biaoti" />
          </el-form-item>

          <el-form-item label="内容摘要">
            <el-input v-model="neibufawenDialog.neirong" type="textarea" :rows="4" placeholder="请输入内容" />
          </el-form-item>

          <el-form-item label="图片">
            <el-upload
              ref="uploadpic"
              :action="uploadUrl"
              :before-upload="beforePicUpload"
              :on-success="uploadPicSuccess"
              list-type="picture-card"
            >
              <i slot="default" class="el-icon-plus" />
              <div slot="file" slot-scope="{file}">
                <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
                <span class="el-upload-list__item-actions">
                  <span v-if="true" class="el-upload-list__item-delete" @click="handleRemovePic(file)"><i
                    class="el-icon-delete"
                  /></span>
                </span>
              </div>
            </el-upload>
          </el-form-item>

          <el-form-item label="附件">
            <div v-for="(item1, idx1) in neibufawenDialog.attaches" :key="idx1">
              {{ item1.name }}
              <br>
            </div>
            <el-upload
              ref="attaches"
              :action="uploadUrl"
              :on-success="uploadAttachSuccess"
              :show-file-list="false"
            >
              <el-button size="small" type="primary" plain>点击上传附件</el-button>
            </el-upload>
          </el-form-item>

          <el-form-item label="分发范围">
            <el-cascader v-model="neibufawenDialog.readers" :options="userList" :props="props" clearable style="width: 100%;"/>
          </el-form-item>

        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="neibufawenDialog.visible = false">关 闭</el-button>
        <el-button type="primary" @click="clickApply()">提 交</el-button>
      </span>
    </el-dialog>

    <el-dialog title="" width="60%" :visible.sync="detailDialog.visible" top="5vh">
      <neibufawen-detail :id="detailDialog.id" />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="(detailDialog.visible = false)">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import { websock } from '@/websock'
import moment from 'moment'
import NeibufawenDetail from '../../components/details/neibufawenDetail.vue'

export default {
  components: { NeibufawenDetail },
  filters: {
    statusFilter(sta) {
      const statusMap = {
        1: 'info',
        2: 'success',
        3: 'danger'
      }
      return statusMap[sta]
    }
  },
  data() {
    return {
      props: { multiple: true },
      list: null,
      listLoading: true,
      pageIndex: 1,
      pageCount: 10,
      dataTotal: 0,
      userList: [],
      uploadUrl: process.env.VUE_APP_BASE_API + '/oa/uploadFile',
      neibufawenDialog: {
        visible: false,
        biaoti: '',
        neirong: '',
        readers: [],
        pics: [],
        attaches: [],
        fileTag: ""
      },
      rangeArr: [],
      detailDialog: {
        visible: false,
        id: 0
      }
    }
  },
  async created() {
    this.getList()
    this.fileTagListFun()

    const res = await websock.getContactList()
    console.log('created', res)
    const userList = []
    for (let i = 0; i !== res.length; i++) {
      userList.push({ value: i + '', label: res[i].name, children: [] })
      for (let j = 0; j !== res[i].userList.length; j++) {
        userList[i].children.push({ value: JSON.stringify({ uid: res[i].userList[j].uid, name: res[i].userList[j].name }), label: res[i].userList[j].name })
      }
    }
    this.userList = userList
  },
  methods: {
    // 获取格式化时间字符串
    getFormatedTimeStr(stamp, str = 'MM-DD HH:mm') {
    	return moment(stamp).format(str)
    },
    // 获取文件类型
    async fileTagListFun(){
      let data = await websock.fileTagList();
      if(data&&data.length) {
        this.rangeArr = data.map((v) => {
          return {
            value: v.id, label: v.name
          }
        });
        this.neibufawenDialog.fileTag = this.rangeArr[0].value
      }
    },
    getList() {
      this.listLoading = true
      websock.neibuFawenRecordWeb({
        pageIndex: this.pageIndex,
        pageCount: this.pageCount
      }).then(
        (data) => {
          this.listLoading = false
          this.list = data.list
          this.dataTotal = data.count
        }
      )
    },
    uploadAttachSuccess(res, file) {
      console.log('upload attach success', res, file)
      if (res.code !== 0) {
        return this.$message.error(res.message || 'error')
      }
      this.neibufawenDialog.attaches.push({ name: file.name, path: res.data })
    },
    uploadPicSuccess(res, file) {
      console.log('upload attach success', res, file)
      if (res.code !== 0) {
        return this.$message.error(res.message || 'error')
      }
      this.neibufawenDialog.pics.push(res.data)
    },
    beforePicUpload(file) {
      const isPic = file.type === 'image/jpeg' || file.type === 'image/png'
      console.log('before pic upload', file.type)
      if (!isPic) this.$message.error('只能上传jpg或png格式')
      return isPic
    },
    handleRemovePic(file) {
      const fileList = this.$refs.uploadpic.uploadFiles
      console.log(fileList)
      const index = fileList.findIndex((fileItem) => {
        return fileItem.uid === file.uid
      })
      fileList.splice(index, 1)
    },
    onPageSizeChange(val) {
      this.pageCount = val
      this.getList()
    },
    onCurrentPageChange(val) {
      this.pageIndex = val
      this.getList()
    },
    // 显示添加员工界面
    showneibufawenDialog() {
      this.neibufawenDialog.visible = true
      this.neibufawenDialog.biaoti = ''
      this.neibufawenDialog.neirong = ''
      this.neibufawenDialog.readers = []
      this.neibufawenDialog.attaches = []
      if (this.$refs.attaches) this.$refs.attaches.uploadFiles = []
    },
    async clickApply() {
      console.log('click apply', this.neibufawenDialog)
      if (!this.neibufawenDialog.biaoti) return this.$message.error('请输入标题')
      if (!this.neibufawenDialog.neirong) return this.$message.error('请输入内容')

      if (this.neibufawenDialog.readers.length == 0) return this.$message.error('请选择分发范围')

      if (this.neibufawenDialog.attaches.length == 0) return this.$message.error('请添加附件')

      const readers = []
      for (let i = 0; i != this.neibufawenDialog.readers.length; i++) {
        readers.push(JSON.parse(this.neibufawenDialog.readers[i][1]))
      }

      try {
        await websock.neibuFawen({
          biaoti: this.neibufawenDialog.biaoti,
          neirong: this.neibufawenDialog.neirong,
          attaches: this.neibufawenDialog.attaches,
          fileTag: this.neibufawenDialog.fileTag,
          readers
        })

        this.$message.success('申请成功,请等待审核')

        this.neibufawenDialog.visible = false

        this.getList()
      } catch (err) {
        this.$message.error(err.message || 'error')
      }
    },
    async revertApply(idx) {
      try {
        await websock.revertNeibuFawen({ id: this.list[idx].id })
        this.list[idx].sta = 4
        this.getList()
      } catch (err) {
        console.error(err)
        this.$message.error({ title: err.message || 'error' })
      }
    },
    seeDetail(id) {
      this.detailDialog.visible = true
      this.detailDialog.id = id
    }
  }
}
</script>

<style>
  .demo-table-expand {
    font-size: 0;
  }

  .demo-table-expand label {
    width: 120px;
    color: #99a9bf;
  }

  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 100%;
  }
</style>
